package cn.shyouchi.wuguanjia.android.ui.event.report;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.event.EventApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.DataChangeEvent;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.event.post.PostEntity;
import cn.shyouchi.wuguanjia.android.ui.event.rank.EventRankEntity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import cn.shyouchi.wuguanjia.android.widget.dialog.TimePickerDialogFragment;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class AddEventReportActivity extends BaseActivity {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.tv_report_time)
    TextView mTvReportTime;

    @BindView(R.id.tv_report_time_dif)
    TextView mTvReportTimeDif;
    @BindView(R.id.tv_report_time_dif_value)
    TextView mTvReportTimeDifValue;
    @BindView(R.id.iv_dif_has_next)
    ImageView mIvDifHasNext;

    @BindView(R.id.tv_sel_order)
    TextView mTvSelOrder;
    @BindView(R.id.tv_sel_order_value)
    TextView mTvSelOrderValue;
    @BindView(R.id.iv_order_has_next)
    ImageView mIvOrderHasNext;
    @BindView(R.id.tv_sel_post)
    TextView mTvSelPost;
    @BindView(R.id.tv_sel_post_value)
    TextView mTvSelPostValue;
    @BindView(R.id.iv_post_has_next)
    ImageView mIvPostHasNext;
    @BindView(R.id.btn_add_report_time)
    Button mBtnAddReportTime;
    @BindView(R.id.rv_report_times)
    RecyclerView mRvReportTime;
    ReportTimeAdapter mReportTimeAdapter;

    List<String> times = new ArrayList<>();
    List<String> mPostList = new ArrayList<>();
    List<String> mRankList = new ArrayList<>();
    List<String> mDiffList = new ArrayList<>();

    EventApi mEventApi;
    String projectId;

    List<PostEntity.ResultMessageBean> postEntities = new ArrayList<>();
    List<EventRankEntity.ResultMessageBean> rankEntities = new ArrayList<>();

    PostEntity.ResultMessageBean postEntity;
    EventRankEntity.ResultMessageBean rankEntity;

    ReportEntity.ResultMessageBean entity;
    boolean isEdit = false;


    @Override
    public int initContentView() {
        return R.layout.activity_add_event_report;
    }

    @Override
    public void initInjector() {
        mEventApi = new EventApi(mContext);
        projectId = getIntent().getStringExtra("projectId");
        entity = getIntent().getParcelableExtra("report");
        mDiffList.add("5分钟");
        mDiffList.add("10分钟");
        mDiffList.add("15分钟");
        mDiffList.add("20分钟");
        mDiffList.add("25分钟");
        mDiffList.add("30分钟");
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        mTopBar.setTitle(getTitle().toString());
        setSupportActionBar(mTopBar.getToolbar());
        mReportTimeAdapter = new ReportTimeAdapter(times);
        mRvReportTime.setLayoutManager(new LinearLayoutManager(mContext));
        mRvReportTime.setAdapter(mReportTimeAdapter);
        mEventApi.getPostList(projectId)
                .subscribeOn(Schedulers.io())
                .map(new Func1<PostEntity, List<PostEntity.ResultMessageBean>>() {
                    @Override
                    public List<PostEntity.ResultMessageBean> call(PostEntity entity) {
                        mPostList.clear();
                        for (PostEntity.ResultMessageBean bean : entity.getResultMessage()) {
                            mPostList.add(bean.getPost());
                        }
                        return entity.getResultMessage();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<List<PostEntity.ResultMessageBean>>(mContext) {
                    @Override
                    public void onNext(List<PostEntity.ResultMessageBean> resultMessageBeen) {
                        postEntities.addAll(resultMessageBeen);
                        mTvSelPostValue.setText(String.format("共%d个岗位", resultMessageBeen.size()));

                        if (isEdit) {
                            for (PostEntity.ResultMessageBean b : resultMessageBeen) {
                                if (entity.getPostsetting().getId() == b.getId()) {
                                    postEntity = b;
                                    mTvSelPostValue.setText(postEntity.getPost());
                                    break;
                                }
                            }
                        }

                        mEventApi.getRankList(projectId)
                                .subscribeOn(Schedulers.io())
                                .map(new Func1<EventRankEntity, List<EventRankEntity.ResultMessageBean>>() {
                                    @Override
                                    public List<EventRankEntity.ResultMessageBean> call(EventRankEntity entity) {
                                        mRankList.clear();
                                        for (EventRankEntity.ResultMessageBean bean : entity.getResultMessage()) {
                                            mRankList.add(bean.getServicesname());
                                        }
                                        return entity.getResultMessage();
                                    }
                                })
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new ProgressSubscriber<List<EventRankEntity.ResultMessageBean>>(mContext) {
                                    @Override
                                    public void onNext(List<EventRankEntity.ResultMessageBean> resultMessageBeanList) {
                                        mTvSelOrderValue.setText(String.format("共%d个班次", resultMessageBeanList.size()));
                                        if (isEdit) {
                                            for (EventRankEntity.ResultMessageBean b : resultMessageBeanList) {
                                                if (entity.getService().getId() == b.getId()) {
                                                    rankEntity = b;
                                                    mTvSelOrderValue.setText(rankEntity.getServicesname());
                                                    break;
                                                }
                                            }
                                        }


                                        rankEntities.addAll(resultMessageBeanList);

                                    }
                                });
                    }
                });


        if (entity != null) {
            mTvReportTimeDifValue.setText(entity.getJetlag());
            ToastUtil.showToast("编辑状态");
            times.clear();
            try {
                JSONArray ja = new JSONArray(entity.getReportingtime());
                for (int i = 0; i < ja.length(); i++) {
                    times.add(ja.getString(i));
                }
                mReportTimeAdapter.notifyDataSetChanged();

            } catch (JSONException e) {
                e.printStackTrace();
            }


            isEdit = true;
        }


    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick({R.id.item_report_time_dif, R.id.item_sel_order, R.id.item_sel_post, R.id.item_report_time,R.id.btn_add_report_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.item_report_time_dif:
                showSelDialog("选择时间误差", mDiffList, view.getId());
                break;
            case R.id.item_sel_order:
                showSelDialog("选择班次", mRankList, view.getId());
                break;
            case R.id.item_sel_post:
                showSelDialog("选择岗位", mPostList, view.getId());
                break;
            case R.id.btn_add_report_time:
            case R.id.item_report_time:
                showTimePicker("添加报岗时间");
                break;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add("保存");
        menuItem.setShowAsAction(2);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("保存")) {
            generateEntityExit();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void generateEntityExit() {

        if (postEntity == null) {
            ToastUtil.showToast("请选择岗位");

            return;
        }
        if (rankEntity == null) {
            ToastUtil.showToast("请选择班次");

            return;
        }
        if (times.isEmpty()) {
            ToastUtil.showToast("请添加报岗时间");
            return;
        }


        if (isEdit) {

            mEventApi.upReport(projectId, String.valueOf(entity.getId()), String.valueOf(postEntity.getId()), String.valueOf(rankEntity.getId()), mTvReportTimeDifValue.getText().toString(), times)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                        @Override
                        public void onNext(BaseRequestResult result) {
                            EventBus.getDefault().post(new DataChangeEvent());
                            finish();
                        }
                    });

        } else {
            mEventApi.addReport(projectId, String.valueOf(postEntity.getId()), String.valueOf(rankEntity.getId()), mTvReportTimeDifValue.getText().toString(), times)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                        @Override
                        public void onNext(BaseRequestResult result) {
                            EventBus.getDefault().post(new DataChangeEvent());
                            finish();
                        }
                    });
        }


    }


    public void showTimePicker(String title) {
        TimePickerDialogFragment mTimePickerDialog;
        mTimePickerDialog = new TimePickerDialogFragment(getSupportFragmentManager(), title, "");
        mTimePickerDialog.setOnTimePickedListener(new TimePickerDialogFragment.onTimePickedListener() {
            @Override
            public void onPicked(String time) {
                times.add(time);

                mReportTimeAdapter.notifyDataSetChanged();
            }
        });
        mTimePickerDialog.showDialog();
    }


    private synchronized void showSelDialog(String title, List<String> sels, final int id) {
        final String[] choices = sels.toArray(new String[sels.size()]);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText(title);
        builder.setCustomTitle(tvTitle);
        builder.setItems(choices, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (id) {
                    case R.id.item_report_time_dif:
                        mTvReportTimeDifValue.setText(choices[which]);
                        break;
                    case R.id.item_sel_order:
                        rankEntity = rankEntities.get(which);
                        mTvSelOrderValue.setText(choices[which]);
                        break;
                    case R.id.item_sel_post:
                        postEntity = postEntities.get(which);
                        mTvSelPostValue.setText(choices[which]);
                        break;

                }
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }
}
